﻿package  {
	
	import flash.display.Sprite;
	import flash.geom.Vector3D;
	import flash.geom.Matrix3D;

	/**
		contains the routines that rotates the abstract Sprite about the registration point.
		
		By keeping this seperate we can neatly apply rotations to both the links and the shape
	*/
	
	public class ObjectRotate extends Sprite {

		private var spObject:Sprite;
		private var shapeModel:ShapeModel;
		private var parentObject;
		
		public function ObjectRotate(parentObject:Object3D, shapeModel:ShapeModel) {
			
			this.parentObject = parentObject;
			this.shapeModel = shapeModel;
			
			spObject = new Sprite();
			this.addChild(spObject); // should add this to the bg sprite board (?)
			
			spObject.rotationX = 0;
			spObject.rotationY = 0;
			spObject.rotationZ = 0; // now this is enabled for 3D transformations
		}
		
		/**
			This is where the 3D rotation processing happens
		*/
		
		public function rotate(rX:Number, rY:Number, rZ:Number)
		{
			var shapeVertices:Vector.<Vector3D> = shapeModel.getVertices();
			var rotatedShapeVertices:Vector.<Vector3D> = shapeModel.getRotatedVertices();
			
			// 3D transformation in each of the axis
			spObject.transform.matrix3D.appendRotation(rX, Vector3D.X_AXIS);
			spObject.transform.matrix3D.appendRotation(rY, Vector3D.Y_AXIS);
			spObject.transform.matrix3D.appendRotation(rZ, Vector3D.Z_AXIS);
			
			// put this transform in a temporary variable
			var objectMatrix:Matrix3D;
			objectMatrix = spObject.transform.matrix3D.clone();
			
			parentObject.clearObjectDisplay();
			
			// apply to the shape and links vertices
			var i:int;
			for (i = 0; i < shapeModel.getNumVertices(); i++) {
				rotatedShapeVertices[i] = objectMatrix.deltaTransformVector(shapeVertices[i]);
			}
			
			var perspectiveDistortion:uint = shapeModel.getPerspectiveDistortion();
			
			// apply the perspective distortion and project.
			for (i = 0; i < shapeModel.getNumVertices(); i++) {
				rotatedShapeVertices[i].w = (perspectiveDistortion + rotatedShapeVertices[i].z) / perspectiveDistortion;
				rotatedShapeVertices[i].project();
			}
			
			// we set this to store locally in shapeModel
			shapeModel.setRotatedVertices(rotatedShapeVertices);
		}
		
		public function reset():void {
			spObject.transform.matrix3D = new Matrix3D();
			rotate(0.0, 0.0, 0.0);
		}
	}
}
